//
//  SelectedViewController.m
//  Vision
//
//  Created by dllo on 16/3/10.
//  Copyright © 2016年 yue_zhang. All rights reserved.
//

#import "SelectedViewController.h"
#import "SelectedTableViewCell.h"
#import "Data.h"
#import "PushAnimation.h"
#import "VideoViewController.h"

@interface SelectedViewController ()<UITableViewDataSource, UITableViewDelegate, UINavigationControllerDelegate>

@property (nonatomic, retain)NSMutableArray *array;
@end

@implementation SDWebImageManager (cache)

- (BOOL)memoryCachedImageExistsForURL:(NSURL *)url {
    NSString *key = [self cacheKeyForURL:url];
    return ([self.imageCache imageFromMemoryCacheForKey:key] != nil) ?  YES : NO;
}
@end

@implementation SelectedViewController

- (void)viewWillAppear:(BOOL)animated {
    self.navigationController.delegate = self;
}

- (id <UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController *)navigationController
                                   animationControllerForOperation:(UINavigationControllerOperation)operation
                                                fromViewController:(UIViewController *)fromVC
                                                  toViewController:(UIViewController *)toVC{
    if ([toVC isKindOfClass:[VideoViewController class]]) {
        PushAnimation *animation = [[PushAnimation alloc]init];
        return animation;
    }else{
        return nil;
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 150, 30)];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.font = [UIFont fontWithName:@"Lobster 1.4" size:25];
    titleLabel.text = @"Vision";
    self.navigationItem.titleView = titleLabel;
    
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    [SVProgressHUD show];
    
    self.array = [NSMutableArray array];
    [self createData];
    [self setTableView];
}

#pragma mark ---------- 数据解析 ----------
- (void)createData {
    // 数据缓存本地
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSLog(@"%@", path);
    NSString *pathData = [path stringByAppendingPathComponent:@"myData"];
    if (![[NSFileManager defaultManager] fileExistsAtPath:pathData]) {
        [[NSFileManager defaultManager] createDirectoryAtPath:pathData withIntermediateDirectories:YES attributes:nil error:nil];
    }
    NSString *pathDataContent = [pathData stringByAppendingPathComponent:@"selected.plist"];
    
    // 数据解析
    [[AFHTTPSessionManager manager] GET:@"http://baobab.wandoujia.com/api/v2/feed?num=7" parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSArray *temp = responseObject[@"issueList"];
        for (NSDictionary *dicF in temp) {
            NSArray *itemList = dicF[@"itemList"];
            NSMutableArray *dataArray = [NSMutableArray array];
            for (NSDictionary *dicS in itemList) {
                if ([dicS[@"type"] isEqualToString:@"video"]) {
                    Data *data = [[Data alloc] init];
                    [data setValuesForKeysWithDictionary:dicS[@"data"]];
                    [dataArray addObject:data];
                }
            }
            [self.array addObject:dataArray];
        }
        [self.selectedTableView reloadData];
        [SVProgressHUD dismiss];
        [NSKeyedArchiver archiveRootObject:self.array toFile:pathDataContent];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        UIAlertController *alertCtrl = [UIAlertController alertControllerWithTitle:@"提醒" message:@"网络连接超时" preferredStyle:UIAlertControllerStyleAlert];
        [alertCtrl addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        }]];
        [self presentViewController:alertCtrl animated:YES completion:^{
            self.array = [NSKeyedUnarchiver unarchiveObjectWithFile:pathDataContent];
            [self.selectedTableView reloadData];
        }];
        [SVProgressHUD dismiss];
    }];
}

#pragma mark ---------- 设置talbeView ----------
- (void)setTableView {
    [self.selectedTableView registerNib:[UINib nibWithNibName:NSStringFromClass([SelectedTableViewCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([SelectedTableViewCell class])];
}

#pragma mark ---------- tableView协议方法 ----------
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.array.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.array[section] count];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return @"section";
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SelectedTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([SelectedTableViewCell class]) forIndexPath:indexPath];
    Data *data = self.array[indexPath.section][indexPath.row];
    [cell.imgView sd_setImageWithURL:[NSURL URLWithString:data.cover[@"detail"]] placeholderImage:[UIImage imageNamed:@"selectedPlaceImage.png"]];
    cell.titleLabel.text = data.title;
    cell.contentLabel.text = [NSString stringWithFormat:@"#%@ / %.2ld' %.2ld\"", data.category, data.duration / 60, data.duration % 60 ];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    self.hidesBottomBarWhenPushed = YES;
    VideoViewController *videoVC = [[VideoViewController alloc] init];
    [self.navigationController pushViewController:videoVC animated:YES];
    videoVC.data = self.array[indexPath.section][indexPath.row];
    self.hidesBottomBarWhenPushed = NO;
}

#pragma mark ---------- 滑动动画 -----------
/**
 *  @author yueJie, 16-03-11 17:03:44
 *
 *  tableViewCell即将出现时触发
 *
 **/
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    Data *data = self.array[indexPath.section][indexPath.row];
    
    if (![[SDWebImageManager sharedManager] memoryCachedImageExistsForURL:[NSURL URLWithString:data.cover[@"detail"]]]) {
        CATransform3D rotation;//3D旋转
        rotation = CATransform3DMakeTranslation(0 ,40 ,20);
        rotation = CATransform3DScale(rotation, 0.9, .9, 1);
        
        rotation.m34 = 1.0/ -600;
        
        cell.layer.shadowColor = [[UIColor blackColor]CGColor];
        cell.layer.shadowOffset = CGSizeMake(10, 10);
        cell.alpha = 0;
        
        cell.layer.transform = rotation;
        
        [UIView beginAnimations:@"rotation" context:NULL];
        //旋转时间
        [UIView setAnimationDuration:0.4];
        cell.layer.transform = CATransform3DIdentity;
        cell.alpha = 1;
        cell.layer.shadowOffset = CGSizeMake(0, 0);
        [UIView commitAnimations];
    }
}

//- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
//    CGFloat sectionHeaderHeight = 40;
//    if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
//        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
//    }
//    else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
//        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
//    }
//}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
